package net.joint_painting.client.logic;

import gwt.g2d.client.graphics.LineCap;
import gwt.g2d.client.graphics.LineJoin;
import gwt.g2d.client.graphics.Surface;
import gwt.g2d.client.graphics.shapes.ShapeBuilder;
import gwt.g2d.client.math.Vector2;
import net.joint_painting.shared.model.Line;
import net.joint_painting.shared.model.Work;

import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.user.client.DOM;

/**
 * @author CAM
 * @version $Revision: 1.0 $
 */
public class Worker {

    /**
     * Method createSurface.
     * 
     * @param work
     *            Work
     * 
     * @return gwt.g2d.client.graphics.Surface
     */
    private static gwt.g2d.client.graphics.Surface createSurface(Work work) {
	gwt.g2d.client.graphics.Surface surface = new gwt.g2d.client.graphics.Surface(
		net.joint_painting.shared.logic.Surface.size,
		net.joint_painting.shared.logic.Surface.size);
	ImageElement e = DOM.createImg().cast();
	e.setSrc(work.getSurface());
	surface.drawImage(e, 0, 0,
		net.joint_painting.shared.logic.Surface.size,
		net.joint_painting.shared.logic.Surface.size);
	return surface;
    }

    /**
     * Method doWork.
     * 
     * @param work
     *            Work
     */
    public static void doWork(Work work) {
	if (work == null)
	    return;
	gwt.g2d.client.graphics.Surface surface = createSurface(work);
	for (Line line : work.getLines())
	    drawLine(line, surface);
	work.setSurface(surface.toDataURL());
    }

    /**
     * Method drawLine.
     * 
     * @param line
     *            Line
     * @param surface
     *            Surface
     */
    private static void drawLine(Line line, Surface surface) {
	surface.setStrokeStyle(line.getColor()).setLineWidth(line.getSize());
	surface.save().setLineCap(LineCap.ROUND).setLineJoin(LineJoin.ROUND);
	surface.strokeShape(new ShapeBuilder().drawLineSegment(
		new Vector2(line.getX1(), line.getY1()),
		new Vector2(line.getX2(), line.getY2())).build());
	surface.restore();
    }

}
